package com.example.demo.web;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.example.demo.calculator.CalculatorEngine;
import com.example.demo.evaluation.EvaluationEngine;
import com.example.demo.pojo.Identity;
import com.example.demo.pojo.Identity_Device;
import com.example.demo.pojo.Identity_Env;
import com.example.demo.pojo.Identity_User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/ztna")
public class ZTNAController {

    @Autowired
    private CalculatorEngine calculatorEngine = new CalculatorEngine();

    @Autowired
    private EvaluationEngine evaluationEngine = new EvaluationEngine();


    @PostMapping("/calculate")
    public int calculate(@RequestBody String data) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        Identity identity = getIdentity(jsonObject);

        return calculatorEngine.trustCalculate(identity);
    }

    @PostMapping("/evaluate")
    public String evaluate(@RequestBody String data){
        JSONObject jsonObject = JSONObject.parseObject(data);
        Identity identity = getIdentity(jsonObject);
        String reqResult = jsonObject.getString("reqResult");

        evaluationEngine.evaluate(identity,reqResult);

        return "evaluate success";
    }



    private Identity getIdentity(JSONObject jsonObject){
        Identity identity = new Identity();
        identity.setIdentity_user(new Identity_User(jsonObject.getString("USER")));
        identity.setIdentity_device(new Identity_Device(jsonObject.getString("MAC")));
        JSONObject envObject = jsonObject.getJSONObject("ENV");
        identity.setIdentity_env(new Identity_Env(envObject.getString("IP"), envObject.getString("OS"),
                envObject.getLong("LAST_LOGIN_TIME"), envObject.getString("VERSION")));

        return identity;
    }
}
